﻿namespace Pp.Repository
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using Core;
    using Core.Extentions;
    using Core.File;
    using Domain.Model;
    using Globalization;
    using NHibernate;
    using NHibernate.Criterion;

    public class ProjectFollowRepository : BaseRepository<ProjectFollow>
    {
        private ProjectRepository _projectRepository;
        private UserRepository _userRepository;
        public ProjectFollowRepository(ISession session, HttpServerUtilityBase serverUtilityBase)
            : base(session, serverUtilityBase)
        {
            _projectRepository = new ProjectRepository(session, serverUtilityBase);
            _userRepository = new UserRepository(session, serverUtilityBase);
        }

        public Result<int> Follow(Guid? projectId, string followerName)
        {
            var follower = _userRepository.GetByUsername(followerName);
            var project = _projectRepository.Get(projectId);
            var follow = new ProjectFollow
            {
                Follower = follower,
                Project = project,
                IsPassive = false,
                Reason = ""
            };
            Save(follow);
            SendMail(CreateMail(Res.Information_project_follow, MailType.ProjectFollow, new List<MailModel>
                                                                            {
                                                                                new MailModel("ProjectName",project.Name),
                                                                                new MailModel("FollowerName",follower.GetFullName()),
                                                                                new MailModel("FollowCount",project.Follows.Count.ToString())
                                                                            }, project.User.MailAdress).Data);
            return Result<int>.AsSuccess(project.Follows.Count);
        }

        public Result<int> CancelFollow(Guid? projectId, string followerName)
        {
            var follow = Get(projectId, followerName);
            Delete(follow);
            return Result<int>.AsSuccess(follow.Project.Follows.Count);
        }

        private ProjectFollow Get(Guid? projectId, string followerName)
        {
            var follow = BaseCriteria
                .CreateAlias("Project", "p")
                .CreateAlias("Follower", "f")
                .Add(Restrictions.Eq("p.Id", projectId))
                .Add(Restrictions.Eq("f.Username", followerName)).List<ProjectFollow>();
            return follow.ToList().FirstOrDefault();
        }
    }
}
